﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using CrossPlatform;
using System.Diagnostics;

namespace TestHarness
{
    public partial class MainTestHarnessForm : Form
    {
        public MainTestHarnessForm()
        {
            InitializeComponent();
        }


        ControlCenterService.SerialOverUSBTools serialUSBTool = new ControlCenterService.SerialOverUSBTools();
        DataAccess.DBMSAccess dbAccess = new DataAccess.DBMSAccess();

        private void MainTestHarnessForm_Load(object sender, EventArgs e)
        {

            DataAccess.DBMSAccess dbAccess = new DataAccess.DBMSAccess();
            labelHeartbeatDBValue.Text = String.Format("Heartbeat Interval = {0}",
                dbAccess.heartbeatIntervalMilliseconds());

            //serialUSBTool.serialPort1.DataReceived +=
            //    new System.IO.Ports.SerialDataReceivedEventHandler(serialPort1_DataReceived);

            serialUSBTool.NewMessageReceived +=
                new ControlCenterService.SerialOverUSBTools.NewMessageReceivedHandler(serialUSBTool_NewMessageReceived);
        }


        void serialUSBTool_NewMessageReceived(object sender, ControlCenterService.SerialOverUSBTools.NewMessageReceivedEventArgs EventArgsParam)
        {
            // capture the new data into local storage
            sumpPumpDataMessageBuffer += EventArgsParam.Key;


            Common.Messages messages = new Common.Messages();
            Common.CrossPlatformMessagesForSumpPump sumpMessages = new Common.CrossPlatformMessagesForSumpPump();

            // test for status message
            bool success = true;
            while(success)
            {
                int RawDistance = -88;
                int CalibratedDistance = -77;
                sumpPumpDataMessageBuffer = sumpMessages.parseSumpPumpStatusMessage(
                    sumpPumpDataMessageBuffer, ref success, ref RawDistance, ref CalibratedDistance, true);
                if (success)
                {
                    dbAccess.writeSumpPumpData(DateTime.Now, RawDistance, CalibratedDistance, serialUSBTool.receiveBuffer);
                }
            }

            // test for event message
            success = true;
            while (success)
            {
                string rawDateTimeAsString = string.Empty;
                string eventType = string.Empty;
                string eventDescription = string.Empty;
                sumpPumpDataMessageBuffer = sumpMessages.parseSumpPumpEventMessage(
                    sumpPumpDataMessageBuffer, ref success, ref rawDateTimeAsString, ref eventType, ref eventDescription, true);

                // if we found an event message, write it to the database and send an email
                if (success)
                {
                    dbAccess.writeSumpPumpEvent(DateTime.Parse(rawDateTimeAsString), eventType, eventDescription);

                    // send the email
                    string sumpPumpEventSubjectLine = String.Format("Sump Pump Event '{0} from server {1}", eventType, Dns.GetHostName());
                    string sumpPumpEventMessage = String.Format("Processed at {0}" + Environment.NewLine + "'{1}'", DateTime.Now.ToLongTimeString(), eventDescription);
                    Debug.Print(sumpPumpEventMessage);
                    //if (!emailUtilities.sendEmail(smtpHost, destinationEmailAddressList, sourceEmailAddress,
                    //    sumpPumpEventSubjectLine, sumpPumpEventMessage))
                    //{
                    //    eventLogMain.WriteEntry("Failed to send email in ServicePollingDeviceTimer_Tick");
                    //}
                }
            }
        }

        
        string sumpPumpDataMessageBuffer = string.Empty;
        void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            Common.Messages messages = new Common.Messages();
            Common.CrossPlatformMessagesForSumpPump sumpMessages = new Common.CrossPlatformMessagesForSumpPump();
            int RawDistance = -88;
            int CalibratedDistance = -77;
            bool success = true;
            sumpPumpDataMessageBuffer += serialUSBTool.serialPort1.ReadExisting();
            sumpPumpDataMessageBuffer = sumpMessages.parseSumpPumpStatusMessage(
                sumpPumpDataMessageBuffer, ref success, ref RawDistance, ref CalibratedDistance, true);
            if (success)
            {
                dbAccess.writeSumpPumpData(DateTime.Now, RawDistance, CalibratedDistance, serialUSBTool.receiveBuffer);
            }
        }

        private void buttonSendBlinkRateTest_Click(object sender, EventArgs e)
        {            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx ");
            request = WebRequest.Create("http://192.168.1.141/900");
            // Set the Method property of the request to POST.
            request.Method = "POST";
            // Create POST data and convert it to a byte array.
            string postData = "This is a test that posts this string to a Web server.";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;
            // Get the request stream.
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.
            dataStream.Close();
            // Get the response.
            WebResponse response = request.GetResponse();
            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();
            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);
            // Read the content.
            string responseFromServer = reader.ReadToEnd();
            // Display the content.
            Console.WriteLine(responseFromServer);
            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();

        }

        private void buttonTestHarness_Click(object sender, EventArgs e)
        {
            CrossPlatform.CrossPlatformHostCommunications hostComms = new CrossPlatform.CrossPlatformHostCommunications();
            MessageBox.Show(hostComms.getConfiguration("deviceID13"));
        }

        private void buttonGetConfigFromWebService_Click(object sender, EventArgs e)
        {
            localhost.ConfigurationService configService = new localhost.ConfigurationService();

            MessageBox.Show(configService.DownloadConfigurationByID("deviceID17"));
        }

        private void buttonSendEmail_Click(object sender, EventArgs e)
        {
        }
        public void sendEmail(string smtpHost, string targetAddress, string emailSubject, string emailMessage)
        {
            try
            {
                System.Diagnostics.Debug.WriteLine(Environment.UserDomainName);
                System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
                //message.To.Add("luckyperson@online.microsoft.com");
                message.To.Add(targetAddress);
                message.Subject = emailSubject;
                message.From = new System.Net.Mail.MailAddress(targetAddress);
                message.Body = emailMessage;
                System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient(smtpHost);
                smtp.Send(message);
            }
            catch (Exception exception)
            {
                MessageBox.Show(string.Format("{0}: {1}", exception.Message, exception.InnerException));
            }
        }

        private void buttonGetDistanceViaUSB_Click(object sender, EventArgs e)
        {
            Common.CrossPlatformMessagesForSumpPump pumpMessages = new Common.CrossPlatformMessagesForSumpPump();
            serialUSBTool.sendChar(Convert.ToChar(pumpMessages.messageRequestingSumpPumpStatusUpdate()));
            //System.Threading.Thread.Sleep(3000); 
            //Application.DoEvents();
            //labelDistanceFromUSB.Text = string.Format("Distance from device via USB = <{0}> at {1}", serialUSB.receiveBuffer, DateTime.Now.ToLongTimeString());
        }

        private void buttonReadDistanceFromUSB_Click(object sender, EventArgs e)
        {
            labelDistanceFromUSB.Text = string.Format("Distance from device via USB = <{0}> at {1}", sumpPumpDataMessageBuffer, DateTime.Now.ToLongTimeString());
            textBoxSumpPumpMessage.Text = sumpPumpDataMessageBuffer;
        }

        private void buttonEncode_Click(object sender, EventArgs e)
        {
            Common.CrossPlatformMessagesForSumpPump sumpMessages = new Common.CrossPlatformMessagesForSumpPump();
            textBoxSumpPumpMessage.Text =  sumpMessages.createSumpPumpStatusMessage(
                int.Parse(textBoxRawDistance.Text)
                , int.Parse(textBoxCalibratedDistance.Text));

        }

        private void buttonDecode_Click(object sender, EventArgs e)
        {
            Common.CrossPlatformMessagesForSumpPump sumpMessages = new Common.CrossPlatformMessagesForSumpPump();
            int RawDistance = -88;
            int CalibratedDistance = -77;
            bool success = true;
            textBoxSumpPumpMessage.Text = 
                sumpMessages.parseSumpPumpStatusMessage(textBoxSumpPumpMessage.Text, ref success, ref RawDistance, ref CalibratedDistance, true);
            textBoxRawDistance.Text = RawDistance.ToString();
            textBoxCalibratedDistance.Text = CalibratedDistance.ToString();
            textBoxSuccess.Text = success.ToString();
        }
    }
}
